import socket
from socket import AF_INET, SOCK_DGRAM
from package import Package, Protocal0825

from binascii import unhexlify, hexlify
from qqtea import decrypt

class Client:
    def __init__(self):
        self.socket = socket.socket(AF_INET, SOCK_DGRAM)
    def call(self, server_ip, protocal, data):
        addr = (server_ip, 8000)
        package = Package(protocal, data)
        self.package = package
        package_data = package.serialize()
        key = package.protocal.qqtea_key
        self.socket.sendto(package_data, addr)
        response = self.socket.recvfrom(1024)
        res_package, server_addr = response
        print(server_addr)
        return res_package 
        # print(package.protocal.analyze(res_package))
    def login(self, server_ip):
        protocal = Protocal0825
        data = {"qq": 414446770, "server_ip": "0.0.0.0"}
        resp = self.call(server_ip, protocal, data)
        result = self.package.protocal.analyze(resp)
        status = result[0:2]
        login_server = result[-8:]
        ret = {
            "success": False,
            "login_server": socket.inet_ntoa(unhexlify(login_server))
        }
        if status == b'00':
            ret["success"] = True
        return ret

if __name__ == '__main__':
    server = "sz9.tencent.com"
    a = Client()
    print(a.login(server))
